package com.dragon.repository.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragon.repository.config.annotation.DataScope;
import com.dragon.repository.entity.Procurement;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

/**
 * <p>
 * 采购单 Mapper 接口
 * </p>
 *
 * @author sy
 * @since 2023-10-23
 */
@Mapper
public interface ProcurementMapper extends BaseMapper<Procurement> {

    @Select("<script>" +
            "select M.* from (" +
            "SELECT a.*, aa.username as procuredAdminName, ad.name as procuredDepartmentName, v.name as vendorName FROM dragon_procurement a " +
            "LEFT JOIN dragon_admin aa on a.procured_admin_id = aa.id " +
            "LEFT JOIN dragon_department ad on a.procured_department_id = ad.id " +
            "LEFT JOIN dragon_vendor v on a.vendor_id = v.id )M where 1 = 1 and M.procured_state = #{procuredState} " +
            "<if test='id != null and id != \"\"'> "+
            " and M.id = #{id} " +
            "</if> " +
            "<if test='search != null and search != \"\"'> "+
            " and M.title like CONCAT('%',#{search},'%')  " +
            "</if> " +
            "<if test='state != null and state != \"\"'> "+
            " and M.status = #{state} " +
            "</if> " +
            "ORDER BY M.create_time DESC " +
            "</script>")
    @DataScope(adminField = "procured_admin_id, admin_id", deptField = "department_id", authCodeString = "purchase")
    Page<Procurement> selectPageByItem(Page<Procurement> procuredPage, Integer id, String search, Integer state, Integer procuredState);

    @Select("SELECT MAX(procured_code) FROM dragon_procurement WHERE procured_code LIKE CONCAT(#{code},'%')")
    String maxRoundInoutNumber(String code);

    @Select("SELECT DISTINCT a.* FROM dragon_procurement a " +
            "LEFT JOIN dragon_procurement_product aa on a.id = aa.procurement_id " +
            "LEFT JOIN dragon_requisition_product aaa on aaa.id = aa.requisition_product_id WHERE aaa.requisition_id = #{id} ")
    Procurement selectCodeByCG(Integer id);

    @Select("select a.* from dragon_procurement a " +
            "LEFT JOIN dragon_procurement_product aa on a.id = aa.procurement_id WHERE aa.requisition_product_id = #{id} ")
    Procurement selectOneByRequisitionProductId(Integer id);

    @Select("select M.* from (" +
            "SELECT a.*, aa.username as procuredAdminName, ad.name as procuredDepartmentName, v.name as vendorName FROM dragon_procurement a " +
            "LEFT JOIN dragon_admin aa on a.procured_admin_id = aa.id " +
            "LEFT JOIN dragon_department ad on a.procured_department_id = ad.id " +
            "LEFT JOIN dragon_vendor v on a.vendor_id = v.id )M where 1 = 1 and M.id = #{id}")
    Procurement selectDetailById(Integer id);
}
